<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Exception;

/**
 * WanlShop地址接口
 */
class Address extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    
    
    /**
     * 获取地址列表
     *
     * @ApiSummary  (WanlShop 地址接口获取地址列表)
     * @ApiMethod   (GET)
	 * 
	 */
    public function getaddress()
    {
        $keywords = $this->request->param('keywords');
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		$list = model('app\api\model\Address')
			->where('user_id', $this->auth->id)
            ->where('name|mobile|address|idcard','like','%'.$keywords.'%')
			->order('updatetime desc')
			->paginate();
		$this->success('返回成功', $list);
    }
    
    /**
     * 修改/新增地址
     *
     * @ApiSummary  (WanlShop 地址接口修改/新增地址)
     * @ApiMethod   (POST)
	 * 
	 * @param string $user_id 用户ID
	 */
    public function address()
    {
        if ($this->request->isPost()) {
			//设置过滤方法
			$this->request->filter(['strip_tags']);
        	$request = $this->request->post();

        	$address = new \app\api\model\Address();
        	$data = $request['data'];
            $validate = new \think\Validate([
                'name|收货人'  => 'require|max:25',
                'province|省' => 'require',
                'mobile|手机号' => 'require',
                'zip_code|邮编' => 'require',
                'email|邮箱' => 'require',
                'country|国家' => 'require',
                'province|州/省' => 'require',
                'city|城市' => 'require',
                'address|地址' => 'require',
              //  'attachment_address|附加地址' => 'require',

            ]);

            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
        	$data['user_id'] = $this->auth->id;
        	$count = $address->where(['user_id'=>$data['user_id']])->count();
			// 操作        	
        	switch ($request['type']) {
				case "edit": 
					if($count <= 1){
						$data['default'] = 1;
						$address->allowField(true)->save($data,['id' => $data['id']]);
						$this->success();
					}else{
						// 更新
						$address->allowField(true)->save($data,['id' => $data['id']]);
						// 单独设置默认，避免非默认消耗资源
						if($data['default'] == 1){
							$list = \app\api\model\Address::all(['user_id'=>$data['user_id']]);
							$list = collection($list)->toArray();
							$itemdata = [];
							foreach($list as $item){
							    if($item['id'] == $data['id']){
							    	$item['default'] = 1;
							    }else{
							    	$item['default'] = 0;
							    }
                                $itemdata[] = [
                                    'id' => $item['id'],
                                    'default' => $item['default'],
                                ];
							}
							$address->allowField(true)->saveAll($itemdata);
						}
						$this->success('ok');
					}
					break;
				case "add": 
					if($count == 0){
						// 新增
						$data['default'] = 1;
                        $address->allowField(true)->save($data);
						$this->success('ok',$address);
					}else{
                        $address->allowField(true)->save($data);
						if($data['default'] == 1){
							$list = \app\api\model\Address::all(['user_id'=>$data['user_id']]);
							$list = collection($list)->toArray();
							$itemdata = [];
							foreach($list as $item){
							    if($item['id'] == $address->id){
							    	$item['default'] = 1;
							    }else{
							    	$item['default'] = 0;
							    }
							    $itemdata[] = [
							        'id' => $item['id'],
							        'default' => $item['default'],
                                ];
							}
							$address->saveAll($itemdata);
						}
						$this->success('ok',[]);
					}
					break;
			}
		} else {
		    $this->error(__('Illegal request'));
		}
    }
	
    /**
     * 删除地址
     *
     * @ApiSummary  (WanlShop 地址接口删除地址)
     * @ApiMethod   (POST)
	 * 
	 * @param string $id 地址ID
	 */
    public function deladdress()
    {
        if ($this->request->isPost()) {
			//设置过滤方法
			$this->request->filter(['strip_tags']);
        	$id = $this->request->post('id');
        	if (!$id) {
	            $this->error(__('Invalid parameters'));
	        }
        	if(model('app\api\model\Address')->where(['id'=>$id,'user_id'=>$this->auth->id])->delete()){
        		$this->success();
        	}else{
        		$this->error('删除失败');
        	}
		} else {
		    $this->error(__('Illegal request'));
		}
    }

    // 智能识别收货地址
    public function autoAddress(){
        $address = $this->request->post('address');
        if(!$address){
            $this->error(__('Please enter address'));
        }
        $detail = [];
        try {
            $detail = \fast\Address::smart_parse($address);
        }catch (Exception $e){
            $this->error('识别未获取到信息');
        }

        $this->success('ok',$detail);
    }
}
